﻿using System;
using System.ComponentModel;
using System.Configuration;

namespace Mbs.Configuration
{
    public class SectionHandler : IConfigurationSectionHandler
    {
        public SectionHandler()
        {
        }

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            return section;
        }
    }

    public class ServiceLocatorSection : ConfigurationSection
    {
        public struct Constance
        {
            public const string SectionName = "SericeLocator";
            public const string Implement = "implement";
        }

        private static IServiceLocator  locator= null;
        internal static IServiceLocator Get()
        {
            if (locator != null)
                return locator;
            var section = ConfigurationManager.GetSection(ServiceLocatorSection.Constance.SectionName) as ServiceLocatorSection;

            if (section != null)
            {
                if (!typeof(IServiceLocator).IsAssignableFrom(section.Implement))
                {
                    throw new ConfigurationErrorsException("Invalid service locator type!");
                }
                locator = Activator.CreateInstance(section.Implement) as IServiceLocator;

                ServiceLocator.Current = locator;
            }

            return locator;
        }


        [ConfigurationProperty(Constance.Implement)]
        [TypeConverter(typeof(TypeNameConverter))]
        public Type Implement
        {
            get
            {
                return (Type)this[Constance.Implement];
            }
        }

        public static string AssemblyName
        {
            get
            {
                var section = ConfigurationManager.GetSection(Constance.SectionName) as ServiceLocatorSection;
                if (section != null)
                    return section.Implement.Assembly.GetName().Name;
                return null;
            }
        }

        public static string ImplementTypeName
        {
            get
            {
                var section = ConfigurationManager.GetSection(Constance.SectionName) as ServiceLocatorSection;
                if (section != null)
                    return section.Implement.FullName;
                return null;
            }
        }
    }
}
